<!doctype html>
<html>
  <head>
    <title>Notifications: Should be able to focus window in onclick event.</title>
    <script src="../resources/testharness.js"></script>
    <script src="../resources/testharnessreport.js"></script>
    <script src="../resources/permissions-helper.js"></script>
    <script src="../resources/user-gesture-utils.js"></script>
  </head>
  <body>
    <script>
      // Tests that Document-bound notifications are able to focus a window in
      // their onclick event. When the test is being run manually, grant
      // Notification permission and click on the notification.
      if (window.testRunner) {
          testRunner.setPopupBlockingEnabled(false);
      }

      function simulateUserClick(x, y) {
          if (window.eventSender) {
              eventSender.mouseMoveTo(x, y);
              eventSender.mouseDown();
              eventSender.mouseUp();
	  }
      }
      function focusWithUserGesture(w) {
          var focus_w = document.createElement('a');
          focus_w.onclick = () => { w.focus(); };
          focus_w.innerText = 'focus_w';
          document.body.appendChild(focus_w);
          simulateUserClick(focus_w.getBoundingClientRect().x,
                            focus_w.getBoundingClientRect().y);
          document.body.removeChild(focus_w);
      }

      async_test(function(test) {
          PermissionsHelper.setPermission('notifications', 'granted').then(test.step_func(function() {
              if (Notification.permission != 'granted') {
                  assert_unreached('No permission has been granted for displaying notifications.');
                  return;
              }

              window.addEventListener('focus', test.step_func(function() {
                  test.done();
              }));

              var childWindow = window.open('about:blank');
              focusWithUserGesture(childWindow);

              var notification = new Notification('My Notification');
              notification.addEventListener('show', test.step_func(function() {
                  if (window.testRunner)
                      testRunner.simulateWebNotificationClick('My Notification');
              }));

              notification.addEventListener('click', test.step_func(function() {
                  window.focus();
              }));

              notification.addEventListener('error', test.step_func(function() {
                  assert_unreached('The error event should not be thrown.');
              }));
          }));
      }, 'Clicking on a notification enables it to focus the window it was created from.');
    </script>
  </body>
</html>
